<?php

class Authenticator extends Object implements IAuthenticator
{

	/**
	 * Performs an authentication
	 *
	 * @param array $credentials
	 * @return Identity
	 * @throws AuthenticationException
	 */
	public function authenticate(array $credentials)
	{
		$username = $credentials[self::USERNAME];
        $password = sha1($credentials[self::PASSWORD]);

        // přečteme záznam o uživateli z databáze
        $row = dibi::fetch('SELECT id_user, real_name, password, role FROM srcms_users WHERE login=%s', $username);

        if (!$row) { // uživatel nenalezen?
            throw new AuthenticationException("Uživatel '$username' nebyl nalezen.", self::IDENTITY_NOT_FOUND);
            return false;
        }

        if ($row->password !== $password) { // hesla se neshodují?
            throw new AuthenticationException("Bylo zadáno nesprávné heslo.", self::INVALID_CREDENTIAL);
            return false;
        }
		
        $data = array("id_user" => $row->id_user);
        
        return new Identity($row->real_name, $row->role, $data); // vrátíme identitu
	}

}